#!/usr/bin/env python
"""Prints latest metars from the wg3 database.
"""

__RCS__ = '$Id$'
__version__ = '$Revision:$'
__initialdate__ = 'December 2008'
__author__ = 'Darren Paul Griffith <http://madphilosopher.ca/>'

# try importing the old, then the new, version of the sqlite module
try:
    from pysqlite2 import dbapi2 as sqlite     # Python 2.4 or earlier
except:
    import sqlite3 as sqlite                   # Python 2.5 or later

import time
import os.path

DATABASE = '/db/code.db'
CODES = ["CYOJ", "CYPE", "CXHP", "CYXD", "CYEG", ]
SQL = "select timestamp,cycle,code from metar where station_id = '%s' order by timestamp desc limit 12; "


HEAD = """<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>metar.ca</title>
  <link rel="stylesheet" href="http://www.w3.org/StyleSheets/Core/Oldstyle" type="text/css">
</head>
<body>"""

TAIL = """
<p><a href="http://madphilosopher.ca/">madphilosopher.ca</a></p>
</body>
</html>"""


if __name__ == '__main__':

    print HEAD

    # generate UTC timestamp
    t = time.gmtime()
    year, month, day, hour, minute = t[0:5]
    timestamp = time.strftime("%a %b %d%H%MZ %Y", t)
    timestamp = time.asctime(t)
    print "<b>Generated: </b><tt>%s UTC</tt>" % timestamp 

    # print the database size
    length = os.path.getsize(DATABASE) / 1024.0 / 1024.0
    print "<b>Database size: </b><tt>%.1f MB</tt><br>" % length 

    # connect to the database
    connection = sqlite.connect(DATABASE)
    c = connection.cursor()

    for station in CODES:

        station = station.upper()
        print
        print "<a name='%s'></a>" % station
        print "<h1>%s</h1>" % station
        print "<font size='-1'>"

        query = SQL % station
        c.execute(query)
        for row in c:
            try:
                timestamp,cycle,code = row
                cycle = int(cycle)
                print "%02d: %s<br>" % (cycle, code)
            except:
                pass
        print "</font>"

    print TAIL
    c.close()
